package com.wangyi.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wangyi.basic.constant.VerifyConstants;
import com.wangyi.basic.exception.BusinessException;
import com.wangyi.basic.jwt.JwtUtils;
import com.wangyi.basic.jwt.LoginData;
import com.wangyi.basic.jwt.RsaUtils;
import com.wangyi.basic.util.AjaxResult;
import com.wangyi.basic.util.HttpUtil;
import com.wangyi.basic.util.MD5Utils;
import com.wangyi.basic.util.StrUtils;
import com.wangyi.system.domain.Menu;
import com.wangyi.user.constant.WxConstants;
import com.wangyi.user.domain.Logininfo;
import com.wangyi.user.domain.User;
import com.wangyi.user.domain.Wxuser;
import com.wangyi.user.dto.BinderDto;
import com.wangyi.user.dto.LoginDto;
import com.wangyi.user.mapper.LogininfoMapper;
import com.wangyi.user.mapper.UserMapper;
import com.wangyi.user.mapper.WxuserMapper;
import com.wangyi.user.service.ILogininfoService;
import com.wangyi.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 账号登录
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String password = loginDto.getPassword();
        Integer loginType = loginDto.getLoginType();
        // 1.校验 - 空值校验
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(loginType)) {
            throw new BusinessException("数据不能为空！！！");
        }

        // 2.校验 - 校验账号
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) { // 账号错误
            throw new BusinessException("账号或密码错误！！！");
        }

        // 3.校验 - 校验密码
        String md5InputPwd = MD5Utils.encrypByMd5(password + logininfo.getSalt());
        if (!md5InputPwd.equals(logininfo.getPassword())) {
            throw new BusinessException("账号或密码错误！！！");
        }

        // 4.状态校验 - 启用，禁用
        if (!logininfo.getDisable()) {
            throw new BusinessException("你的账号被冻结，请联系管理员！！！");
        }
        
//        // 5.生成key【token】 将key和登录信息对象保存到redis
//        String token = UUID.randomUUID().toString();
//        // 去掉密码和盐值 - 安全
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo",logininfo);

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }

    /**
     * 微信登录
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        // 1.根据code发送请求获取token和openid
        String url = WxConstants.GET_ACK_URL
                .replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        String jsonStr = HttpUtil.httpGet(url);
//        System.out.println(jsonStr);

        // {"access_token":"57_3R0PHzOIKX6brh1TbBZKqwsOCHugjzrJeDZgssoAmsF_UFOq-TSTXE3tmZBUr7VIZ_eP71LhIzOeLeh4gua3vVligjDuBCjRiImEAPSAwqc",
        //              "openid":"oa9wA01X4TNik8bbXWklIyArUZ5c",}
        // 2.将响应的json字符串 转成 json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        // 3.通过openid去t_wxuser中查询
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);

        if (wxuser != null && wxuser.getUserId() != null) { // 绑定了
            //4.有 绑定过 - 直接免密登录【获取logininfo对象 登录】
            Logininfo logininfo = logininfoMapper.loadLogininfoByUserId(wxuser.getUserId());

            Map<String, Object> map = loginSuccessJwtHandler(logininfo);

            return AjaxResult.me().setResultObj(map);
        } else {
            //5.没有 - 需要跳转页面绑定 - 响应给前端进行跳转
            Map<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid",openid);
            return AjaxResult.me().setSuccess(false).setResultObj(map);
        }
    }

    /**
     * 微信绑定业务
     * @param binderDto
     * @return
     */
    @Override
    public AjaxResult wechatBinder(BinderDto binderDto) {
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String accesstoken = binderDto.getAccessToken();
        String openId = binderDto.getOpenId();
        // 校验
        // 1.校验 - 空置校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("数据不能为空");
        }

        // 2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get(VerifyConstants.BINDER_PREFIX + phone);
        if(redisCode==null) {
            throw new BusinessException("验证码过期");
        }
        // 3.校验 - 验证码是否正确
        if (!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())) {
            throw new BusinessException("验证码错误");
        }


        // 绑定用户：t_wxUser【user_id】 绑定 t_user
        // 4.获取WxUser - 发送第三个请求 - json字符串
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN",accesstoken)
                .replace("OPENID",openId);

        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr); //user_id

        // 5.通过phone查询User
        User user = userMapper.loadByPhone(phone);
        //5.1.如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if (user == null) {
            user = phone2User(phone);
            Logininfo logininfoTmp= user2Logininfo(user);

            logininfoMapper.save(logininfoTmp);
            user.setLogininfoId(logininfoTmp.getId());
            userMapper.save(user);
        }
        // 6.将User对象的id设置到WxUser对象中
        wxuser.setUserId(user.getId());
        // 7.将WxUser对象添加到数据库
        wxuserMapper.save(wxuser);

        // 8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数据密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        LoginData loginData = new LoginData();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();
        try {
            // 1.获取logininfo
            if (logininfo.getType()==0) { // 管理员
                // 2.获取当前登陆人的所有权限 - sn
                List<String> permissions = logininfoMapper.loadPermissionsByLogininfoId(logininfo.getId());
                // 3.获取当前登陆人的所有菜单 - 【难度】
                List<Menu> menus = logininfoMapper.loadMenusByLogininfoId(logininfo.getId());
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);

                map.put("permissions", permissions);
                map.put("menus", menus);
            }
            // 4.通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300);

            // 5.装到map返回
            map.put("token", jwtToken);
            map.put("logininfo", logininfo);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
